require 'json'
require 'spoule/json'
require 'spoule/method'

module Spoule
  class Resource
    include Spoule::Json

    def initialize(name)
      @name = name
      @methods = []
      @resources = []
    end

    def <<(o)
      case o
      when Spoule::Method::Base
        @methods << o
      when Spoule::Resource
        @resources << o
      else
        raise "Cannot accept objects of type #{o.class}!"
      end
    end
    
    def to_json(*opts)
      s  = ''
      s += _format_json_prefix(@name, opts)
      
      if !@methods.empty?
        s += _format_json_prefix('methods', opts)
        s += @methods.inject([]) {|a,x| a << x.to_json(opts) }.join(',')
        s += _format_json_suffix
      end

      if !@resources.empty?
        s += _format_json_prefix('resources', opts)
        s += @resources.inject([]) {|a,x| a << x.to_json(opts) }.join(',')
        s += _format_json_suffix
      end

      s += _format_json_suffix
      return s
    end
  end
end # module Spoule
